/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pku.lbs.web;

import com.blipsystems.blipnet.api.util.BlipNetSecurityManager;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

/**
 *
 * @author yongchao
 */
public class VoiceWeb {

    static private VoiceWeb instance = null;

    private VoiceWeb() {
        System.setProperty("freetts.voices","com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
    }

    static public VoiceWeb getInstance() {
        if (instance == null) {
            instance = new VoiceWeb();
        }
        return instance;
    }

    private void listAllVoices() {
        System.out.println();
        System.out.println("All voices available:");
        VoiceManager voiceManager = VoiceManager.getInstance();
        Voice[] voices = voiceManager.getVoices();
        for (int i = 0; i < voices.length; i++) {
            System.out.println("    " + voices[i].getName() + " (" + voices[i].getDomain() + " domain)");
        }
    }

    private void speech(String content) {
        listAllVoices();

        String voiceName = "kevin16";
        VoiceManager voiceManager = VoiceManager.getInstance();
        Voice helloVoice = voiceManager.getVoice(voiceName);

        if (helloVoice == null) {
            System.err.println(
                "Cannot find a voice named "
                + voiceName + ".  Please specify a different voice.");
            System.exit(1);
        }
        helloVoice.allocate();
        helloVoice.speak( content );
        helloVoice.deallocate();
    }

    public String doBroadcast(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String posX = request.getParameter("pos_x");
        String posY = request.getParameter("pos_y");
        String speechText = request.getParameter("speech");

        speech(speechText);
        JSONObject json = new JSONObject();
        json.put("RETURN", true);

        return json.toString();
    }
}
